package com.theaf.core.utils;

import com.theaf.core.cache.ThreadLocalHelper;
import org.codehaus.jackson.map.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import java.util.Map;


/**
 * HTTP工具类
 * @author songwenke
 * @date 2017-11-15
 */
 public class HttpHelper {

	public static HttpServletRequest getHttpServletRequest()
	{
		return HttpHolder.getHttpHolder().getRequest();
	}
	
	public static HttpServletResponse getHttpServletResponse()
	{
		return HttpHolder.getHttpHolder().getResponse();
	}
	
	public static HttpSession getHttpSession()
	{
		return HttpHolder.getHttpHolder().getRequest().getSession(false);
	}
	
	public static Object getSessionAttr(String key)
	{
		return getHttpSession().getAttribute(key);
	}
	
	public static void setSessionAttr(String key,Object o)
	{
		getHttpSession().setAttribute(key, o);
	}

	/**
	 * 获取当前IP
	 * @return
	 */
	public static String getIp(HttpServletRequest request)
	{
		if(request==null){
			request = getHttpServletRequest();
		}
		// 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址

		String ip = request.getHeader("X-Forwarded-For");

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
					System.out.println("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
					System.out.println("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
				System.out.println("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
					System.out.println("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
					System.out.println("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!("unknown".equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}
	
	public static void init(HttpServletRequest request,HttpServletResponse response) {
		HttpHolder httpHolder = HttpHolder.getHttpHolder();
		if( httpHolder == null )
		{
			httpHolder = new HttpHolder();
			HttpHolder.setHttpHolder(httpHolder);
		}				
		httpHolder.setRequest(request);
		httpHolder.setResponse(response);
	}
	public static void clear()
	{
		HttpHolder.clear();
	}
	 static class HttpHolder {
		 
		 private static final String HTTPHELPER_HTTPHOLDER = "HTTPHELPER_HTTPHOLDER";
			private HttpServletRequest request;
			private HttpServletResponse response;

			public HttpServletRequest getRequest() {
				return request;
			}
			
			public void setRequest(HttpServletRequest request) {
				this.request = request;
			}

			
			public HttpServletResponse getResponse() {
				return response;
			}

			public void setResponse(HttpServletResponse response) {
				this.response = response;
			}

			public static HttpHolder getHttpHolder()
			{
				return (HttpHolder) ThreadLocalHelper.get(HTTPHELPER_HTTPHOLDER);
			}
			private static void setHttpHolder(HttpHolder h)
			{
				ThreadLocalHelper.set(HTTPHELPER_HTTPHOLDER,h);
			}
			public static void clear()
			{
				HttpHolder h = getHttpHolder();
				if( h != null )
				{
					h.request = null;	
					h.response = null;
				}
				ThreadLocalHelper.del(HTTPHELPER_HTTPHOLDER);
			}
	}

	/**
	 * HTTP请求
	 * @param path
	 * @param submit
	 * @return
	 * @throws Exception
	 */
	public static String post(String path, Map submit) throws Exception{
		URL url = new URL(path);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setRequestMethod("POST");
		con.setReadTimeout(3000);
		con.setConnectTimeout(3000);
		con.setRequestProperty("Content-Type", "text/plain");
		if(submit!=null) {
			ObjectMapper objMapper = new ObjectMapper();
			OutputStream out = con.getOutputStream();
			String send =objMapper.writeValueAsString(submit);
			out.write(send.getBytes("UTF-8"));
			out.flush();
			out.close();
		}else{
			con.connect();
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(con
				.getInputStream(),"UTF-8"));
		String ret = "";
		String line = "";
		for (line = br.readLine(); line != null; line = br.readLine()) {
			ret+=line;
		}
		return ret;
	}

}
